package com.ihrm.system.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.User;
import com.ihrm.system.mapper.RoleMapper;
import com.ihrm.system.mapper.UserMapper;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
public class UserService extends BaseService<User> {
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private IdWorker idWorker;
	/**
	 * 1.保存用户
	 */
	public void save(User user){
		//设置主键
		String id = idWorker.nextId() + "";
		//md5加密密码
		String password = new Md5Hash("123456", user.getMobile(), 3).toString();
		user.setLevel("user");
		user.setPassword(password);//设置初始密码
		user.setEnableState(1);
		user.setId(id);
		userMapper.save(user);
	}


	/**
	 * 2.根据id更新用户
	 */
	public void update(User user){
		//1.根据id查询用户
		User userDb = userMapper.findById(user.getId()).get();
		//2.修改用户属性，更新
		userDb.setUsername(user.getUsername());
		user.setPassword(user.getPassword());
		userDb.setDepartmentId(user.getDepartmentId());
		userDb.setDepartmentName(user.getDepartmentName());
		userMapper.save(userDb);
	}

	/**
	 * 3.根据id查询用户
	 */
	public User findById(String id){
		return userMapper.findById(id).get();
	}

	/**
	 * 4.查询全部用户列表
	 *   参数：map集合的形式
	 *      hasDept
	 *      departmentId
	 *      companyId
	 */
	public Page findAll(Map<String, Object> map,int page, int size){
        //1.需要查询条件
		Specification<User> spec = new Specification<User>() {

			/**
			 * 动态拼接查询条件
			 * @param root
			 * @param query
			 * @param cb
			 * @return
			 */
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				//根据请求的companyId是否为空构造查询条件
				if(!StringUtils.isEmpty(map.get("companyId"))){
					list.add(cb.equal(root.get("companyId").as(String.class),(String)map.get("companyId")));
				}

				//根据请求的departmentId是否为空构造查询条件
				if(!StringUtils.isEmpty(map.get("departmentId"))){
					list.add(cb.equal(root.get("departmentId").as(String.class),(String)map.get("companyId")));
				}


				if(!StringUtils.isEmpty(map.get("hasDept"))){
					//根据请求的hasDept判断  是否分配部门 0未分配(departmentId==null) 1已分配(departmentId!=null)
					if("0".equals((String)map.get("hasDept"))){
						list.add(cb.isNull(root.get("departmentId")));
					}else{
						list.add(cb.isNotNull(root.get("departmentId")));
					}
				}
				return cb.and(list.toArray(new Predicate[list.size()]));
			}
		};

		//2.分页
		return userMapper.findAll(spec, PageRequest.of(page-1, size)); // 修复分页构造方式
	}

	/**
	 * 5.根据id删除用户
	 */
	public void deleteById(String id){
		userMapper.deleteById(id);
	}

	/**
	 * 6.为用户分配角色
	 */
	@Autowired
	private RoleMapper roleMapper;
	public void assignRoles(String userId, List<String> roleIds) {
		//1.根据id查询用户
		User userDb = userMapper.findById(userId).get();

		//2.设置用户的角色集合
		Set<Role> roles = new HashSet<>();
		for (String roleId : roleIds) {
			Role role = roleMapper.findById(roleId).get();
			roles.add(role);
		}
		//设置用户和角色集合之间的关系
		userDb.setRoles(roles);
		//3.更新用户集合
		userMapper.save(userDb);
	}

	/*根据mobile查询用户*/
	public User findByMobile(String mobile) {
		return userMapper.findByMobile(mobile);
	}
}
